package cn.ticsmyc.tools.beanCreate;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.NoOp;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * 根据类加载器得到的Class对象，生成bean的实例
 * 依赖
 *          <dependency>
 *             <groupId>cglib</groupId>
 *             <artifactId>cglib</artifactId>
 *             <version>3.2.5</version>
 *         </dependency>
 * @author Ticsmyc
 * @date 2020-12-22 18:02
 */
public class BeanCreaterUtil {


    public static <T> T getInstance(Class<T> clazz) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        Constructor<T> constructor = clazz.getConstructor(null);
        return (T)constructor.newInstance();
    }
    public static <T> T getInstance(Constructor ctr, Object[] args) throws IllegalAccessException, InvocationTargetException, InstantiationException {
        return (T)ctr.newInstance(args);
    }


    public static <T> T getInstanceByCglib(Class<T> clazz){
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(clazz);
        //直接调原方法
        enhancer.setCallback(NoOp.INSTANCE);
        return (T)enhancer.create();
    }
    public static <T> T getInstanceByCglib(Class<T> clazz, Constructor ctr, Object[] args){
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(clazz);
        //直接调原方法
        enhancer.setCallback(NoOp.INSTANCE);
        return (T)enhancer.create(ctr.getParameterTypes(),args);
    }

}
